package com.ofek.applicationbase.forms;

import java.lang.reflect.Field;

import com.ofek.applicationbase.utils.Log;
import com.ofek.applicationbase.utils.ReflectionUtils;

public class FieldQConnector extends QuestionViewController {
	private final Field field;
	private Object object;

	public FieldQConnector(final String fieldName, final Object model,
			final QuestionView toControl) throws NoSuchFieldException, IllegalArgumentException, IllegalAccessException {
		super(toControl);
		field = ReflectionUtils.getField(model.getClass(),fieldName);
		field.setAccessible(true);
		object = model;
		setDefaultAnswer(field.get(model));
		syncWithField(true);
		syncWithField(false);
	}


	@Override
	protected void onAnswerChanged(final Object t) {
		try {
			Log.d("Setting field "+field.getName()+ "\nof object "+object + "\nwith value "+t);
			field.set(object, question.getAnswer());
		} catch (final Exception e) {
			e.printStackTrace();
		}
	}
	/**
	 * 
	 * @param syncDirection - true - syncs UI by Model, false syncs Model by UI.
	 */
	public void syncWithField(final boolean syncDirection) {
		try {
			if (syncDirection) setDefaultAnswer(field.get(object));
			else field.set(object, question.getAnswer());
		} catch (final Exception e) {
			e.printStackTrace();
		} 
	}

	public void switchModel(final Object newModel,final boolean syncDirection) {
		object = newModel;
		syncWithField(syncDirection);
	}
}
